<template>
    <div>
        <Card class="search" shadow>
            <Input prefix="ios-contact" placeholder="Enter name" style="width: auto"/>
        </Card>
        <Card shadow>
            <div class="tb-header">
                <RefreshButton :refreshList="getTableData"></RefreshButton>
                <Button type="primary" size="small" icon="md-add" style="margin-right: 5px" @click="add">新增</Button>
                <Button type="success" size="small" icon="ios-cloud-upload" style="margin-right: 5px"
                        @click="deploymentFile">部署流程文件
                </Button>
            </div>

            <Table :height="400" size="small" :columns="columns" :data="tableData">
                <template slot-scope="{ row, index }" slot="action">
                    <Button type="primary" size="small" @click="onlineDesign(row.id)" style="margin-right: 5px">在线设计
                    </Button>
                    <Button type="success" size="small" @click="deployment(row.id)" style="margin-right: 5px">部署发布
                    </Button>
                    <Button type="warning" size="small" @click="downloadXml(row.id,row.name)" style="margin-right: 5px">
                        导出XML
                    </Button>
                    <Button type="error" size="small" @click="del(row.id,row.name)" style="margin-right: 5px">删除
                    </Button>
                </template>
            </Table>
            <Pagination
                    ref="pagination"
                    size="small"
                    :sizer="true"
                    :page.sync="listQuery.pageNumber"
                    :rows.sync="listQuery.pageSize"
                    :total="total"
                    @on-change="getTableData"/>
        </Card>

        <Modal v-model="addModalShow" title="编辑" @on-ok="submit" @on-cancel="addModalShow=false">
            <Form ref="formInline" :model="formData" :rules="rules" :label-width="80">
                <FormItem prop="name" label="名称">
                    <Input type="text" v-model="formData.name" placeholder="名称"/>
                </FormItem>
                <FormItem prop="key" label="模型Key">
                    <Input type="text" v-model="formData.key" placeholder="模型Key"/>
                </FormItem>
                <FormItem label="备注">
                    <Input type="text" v-model="formData.description" placeholder="备注"/>
                </FormItem>
            </Form>
        </Modal>

        <Modal v-model="fileModalShow"
               title="部署流程文件"
               @on-cancel="fileModalShow=false">
            <Upload :show-upload-list="false"
                    type="drag"
                    :action="uploadPath"
                    :on-progress="onProgress"
                    :on-success="onSuccess">
                <div style="padding: 20px 0">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>点击或拖拽文件上传</p>
                    <i style="color: #dcdeee;">请选择BPMN文件，仅支持.bpmn、.bpmn20.xml格式文件</i>
                </div>
            </Upload>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>
    import axios from 'axios'
    import {findModelPage, createModel, deploy, delModel} from '@/api/workflow';
    import Pagination from '../components/Pagination' // 分页插件
    import {formatDatetime} from '../../utils/dateUtil'
    import RefreshButton from '../components/RefreshButton' // 分页插件
    import { getAccessToken } from '@/utils/auth'

    export default {
        name: "Design",
        components: {
            Pagination,RefreshButton
        },
        data() {
            return {
                columns: [
                    {
                        title: '名称',
                        key: 'name'
                    },
                    {
                        title: '标识KEY',
                        key: 'key'
                    },
                    {
                        title: '描述',
                        key: 'description'
                    },
                    {
                        title: '版本',
                        key: 'version',
                        width: 60
                    },
                    {
                        title: '创建时间',
                        key: 'created',
                        width: 150
                    },
                    {
                        title: '创建人',
                        key: 'createdByName'
                    },
                    {
                        title: '更新时间',
                        key: 'lastUpdated',
                        width: 150
                    },
                    {
                        title: '更新人',
                        key: 'lastUpdatedByName'
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 320,
                        align: 'center'
                    }
                ],
                tableData: [],
                listQuery: {
                    pageNumber: 1,
                    pageSize: 10
                },
                total: 0,
                addModalShow: false,
                formData: {},
                rules: {
                    name: [
                        {required: true, message: '请输入名称', trigger: 'blur'}
                    ],
                    key: [
                        {required: true, message: '请输入模型Key', trigger: 'blur'}
                    ],
                },
                fileModalShow: false,
                uploadPath: process.env.VUE_APP_BASE_API + "/workflow/resource/importModel"
            }
        },
        created() {
            this.getTableData();
        },
        methods: {
            async getTableData() {
                this.tableData = [];
                this.total = 0;
                let params = this.listQuery
                let res = await findModelPage(params);
                if (res.success) {
                    this.tableData = res.result.records;
                    this.total = res.result.total;
                }
            },
            //在线设计
            onlineDesign(id) {
                // 不打开新页面
                // this.$router.push({name: 'modeler', query: {modelId: id}})
                // 打开新页面
                let routeModeler = this.$router.resolve({name: 'modeler', query: {modelId: id}})
                window.open(routeModeler.href, '_blank');
            },
            //部署流程文件
            deploymentFile() {
                this.fileModalShow = true;
            },
            //文件上传时的钩子
            onProgress(item) {
                let promise = new Promise(resolve => {
                    this.$nextTick(function () {
                        resolve(true);
                    });
                });
            },
            //文件上传成功时的钩子
            onSuccess(res) {
                this.fileModalShow = false;
                this.$layer.msg(res.message, {icon: 1, time: 3});
                this.getTableData();
            },
            //新增
            add() {
                this.addModalShow = true;
            },
            submit() {
                this.$refs['formInline'].validate(async valid => {
                    if (valid) {
                        this.formData.modelType = 0;
                        let res = await createModel(this.formData);
                        if (res.success) {
                            this.$layer.msg(res.message, {icon: 1, time: 3});
                            this.getTableData();
                        }
                    }
                });
            },
            //部署发布
            async deployment(id) {
                let res = await deploy(id);
                if (res.success) {
                    this.$layer.msg(res.message, {icon: 1, time: 3});
                }
            },
            //下载xml
            downloadXml(id, name) {
                const url = process.env.VUE_APP_BASE_API + `/workflow/resource/downloadXml/${id}`;
                axios({
                    method: 'GET',
                    url: url,
                    responseType: 'blob',
                    headers: {
                        'accessToken': getAccessToken()
                    }
                }).then((data) => {
                    if (!data) {
                        return;
                    }
                    let url = window.URL.createObjectURL(new Blob([data.data]));
                    let link = document.createElement('a');
                    link.style.display = 'none';
                    link.href = url;
                    link.setAttribute('download', name + formatDatetime(new Date(), "yyyyMMddhhmmss") + '.bpmn20.xml');
                    document.body.appendChild(link);
                    link.click();
                }).catch(response => {
                    this.$layer.msg(res.message, {icon: 1, time: 3});
                });
            },
            //删除
            del(id, name) {
                this.$layer.confirm('你确定要删除流程【' + name + '】?', {icon: 3, title: '提示'}, async (index) => {
                    this.$layer.close(index);
                    let res = await delModel(id);
                    if (res.success) {
                        this.$layer.msg(res.message, {icon: 1, time: 3});
                        this.getTableData();
                    }
                });
            }
        }
    }
</script>

<style scoped>

</style>
